// src/main/java/org/example/backend/controller/InternshipMaterialController.java
package org.example.backend.controller;

import jakarta.validation.Valid;
import org.example.backend.dto.InternshipMaterialDetailDto;
import org.example.backend.dto.InternshipMaterialDto;
import org.example.backend.dto.PageResponseDto;
import org.example.backend.entity.InternshipMaterial;
import org.example.backend.entity.Student;
import org.example.backend.entity.User;
import org.example.backend.exception.BusinessException;
import org.example.backend.service.InternshipMaterialService;
import org.example.backend.service.StudentService;
import org.example.backend.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/internship-materials")
@CrossOrigin
public class InternshipMaterialController {

    private static final Logger logger = LoggerFactory.getLogger(InternshipMaterialController.class);

    private final InternshipMaterialService internshipMaterialService;
    private final StudentService studentService;
    private final UserService userService;

    public InternshipMaterialController(InternshipMaterialService internshipMaterialService,
                                      StudentService studentService,
                                      UserService userService) {
        this.internshipMaterialService = internshipMaterialService;
        this.studentService = studentService;
        this.userService = userService;
    }

    /**
     * 学生提交实习材料
     */
    @PostMapping
    @PreAuthorize("hasRole('STUDENT')")
    public ResponseEntity<?> submitMaterial(@Valid @RequestBody InternshipMaterialDto materialDto) {
        try {
            // 获取当前认证用户
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();

            // 根据用户名获取用户信息
            User user = userService.getUserByUsername(username);

            // 获取学生信息
            Student student = studentService.getStudentByUserId(user.getId());

            // 提交材料
            InternshipMaterial material = internshipMaterialService.submitMaterial(materialDto, student.getId());

            Map<String, Object> response = new HashMap<>();
            response.put("message", "实习材料提交成功");
            response.put("material", material);

            return ResponseEntity.ok(response);
        } catch (BusinessException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        } catch (Exception e) {
            logger.error("提交实习材料失败", e);
            return ResponseEntity.badRequest().body("提交失败：" + e.getMessage());
        }
    }

    /**
     * 学生更新已提交的实习材料
     */
    @PutMapping("/{materialId}")
    @PreAuthorize("hasRole('STUDENT')")
    public ResponseEntity<?> updateMaterial(@PathVariable Long materialId,
                                          @Valid @RequestBody InternshipMaterialDto materialDto) {
        try {
            // 获取当前认证用户
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();

            // 根据用户名获取用户信息
            User user = userService.getUserByUsername(username);

            // 获取学生信息
            Student student = studentService.getStudentByUserId(user.getId());

            // 更新材料
            InternshipMaterial material = internshipMaterialService.updateMaterial(materialId, materialDto, student.getId());

            Map<String, Object> response = new HashMap<>();
            response.put("message", "实习材料更新成功");
            response.put("material", material);

            return ResponseEntity.ok(response);
        } catch (BusinessException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        } catch (Exception e) {
            logger.error("更新实习材料失败", e);
            return ResponseEntity.badRequest().body("更新失败：" + e.getMessage());
        }
    }

    /**
     * 学生获取自己提交的材料列表（包含实习相关信息）
     */
    @GetMapping("/my")
    @PreAuthorize("hasRole('STUDENT')")
    public ResponseEntity<PageResponseDto<InternshipMaterialDetailDto>> getMyMaterialsWithDetails(
            @RequestParam(required = false) Integer type,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            // 获取当前认证用户
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();

            // 根据用户名获取用户信息
            User user = userService.getUserByUsername(username);

            // 获取学生信息
            Student student = studentService.getStudentByUserId(user.getId());

            // 获取材料列表
            Page<InternshipMaterialDetailDto> materials = internshipMaterialService.getMyMaterialsWithDetails(
                    student.getId(), type, page, size);

            PageResponseDto<InternshipMaterialDetailDto> response = new PageResponseDto<>(
                    materials.getContent(),
                    materials.getTotalElements(),
                    materials.getTotalPages(),
                    page,
                    size
            );

            return ResponseEntity.ok(response);
        } catch (BusinessException e) {
            return ResponseEntity.badRequest().body(null);
        } catch (Exception e) {
            logger.error("获取实习材料列表失败", e);
            return ResponseEntity.badRequest().body(null);
        }
    }

    /**
     * 获取实习下的所有材料（包含学生姓名）
     */
    @GetMapping("/internship/{internshipId}")
    public ResponseEntity<PageResponseDto<InternshipMaterialDetailDto>> getMaterialsByInternshipWithStudentName(
            @PathVariable Long internshipId,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            Page<InternshipMaterialDetailDto> materialPage = internshipMaterialService.getMaterialsByInternshipWithStudentName(
                    internshipId, page, size);

            PageResponseDto<InternshipMaterialDetailDto> response = new PageResponseDto<>(
                    materialPage.getContent(),
                    materialPage.getTotalElements(),
                    materialPage.getTotalPages(),
                    page,
                    size
            );

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("获取实习材料列表失败", e);
            return ResponseEntity.badRequest().body(null);
        }
    }

    /**
     * 获取材料详情（包含学生姓名和实习相关信息）
     */
    @GetMapping("/{materialId}")
    public ResponseEntity<?> getMaterialWithDetails(@PathVariable Long materialId) {
        try {
            InternshipMaterialDetailDto materialDto = internshipMaterialService.getMaterialWithDetails(materialId);
            return ResponseEntity.ok(materialDto);
        } catch (Exception e) {
            logger.error("获取材料详情失败", e);
            return ResponseEntity.badRequest().body("获取材料详情失败：" + e.getMessage());
        }
    }

    /**
     * 学生删除待审核的材料
     */
    @DeleteMapping("/{materialId}")
    @PreAuthorize("hasRole('STUDENT')")
    public ResponseEntity<?> deleteMaterial(@PathVariable Long materialId) {
        try {
            // 获取当前认证用户
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();

            // 根据用户名获取用户信息
            User user = userService.getUserByUsername(username);

            // 获取学生信息
            Student student = studentService.getStudentByUserId(user.getId());

            // 删除材料
            internshipMaterialService.deleteMaterial(materialId, student.getId());

            return ResponseEntity.ok("实习材料删除成功");
        } catch (BusinessException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        } catch (Exception e) {
            logger.error("删除实习材料失败", e);
            return ResponseEntity.badRequest().body("删除失败：" + e.getMessage());
        }
    }

    /**
     * 教师/企业审核实习材料
     */
    @PutMapping("/{materialId}/review")
    @PreAuthorize("hasRole('TEACHER') or hasRole('COMPANY')")
    public ResponseEntity<?> reviewMaterial(@PathVariable Long materialId,
                                          @RequestParam Integer status,
                                          @RequestParam(required = false) String rejectReason) {
        try {
            // 获取当前认证用户
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();

            // 根据用户名获取用户信息
            User user = userService.getUserByUsername(username);

            // 审核材料
            InternshipMaterial material = internshipMaterialService.reviewMaterial(materialId, user.getId(), status, rejectReason);

            String message = status == 1 ? "材料审核通过" : "材料审核拒绝";
            Map<String, Object> response = new HashMap<>();
            response.put("message", message);
            response.put("material", material);

            return ResponseEntity.ok(response);
        } catch (BusinessException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        } catch (Exception e) {
            logger.error("审核实习材料失败", e);
            return ResponseEntity.badRequest().body("审核失败：" + e.getMessage());
        }
    }

    /**
     * 管理员获取所有材料列表
     */
    @GetMapping
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<PageResponseDto<InternshipMaterial>> getAllMaterials(
            @RequestParam(required = false) Integer status,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            Page<InternshipMaterial> materialPage = internshipMaterialService.getAllMaterials(status, page, size);

            PageResponseDto<InternshipMaterial> response = new PageResponseDto<>(
                    materialPage.getContent(),
                    materialPage.getTotalElements(),
                    materialPage.getTotalPages(),
                    page,
                    size
            );

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("获取材料列表失败", e);
            return ResponseEntity.badRequest().body(null);
        }
    }
}
